'use strict';

angular.module('BC')
    .service('BCService', ['$http', '$q', 'Authentication', 'BaseFunction', 'EntityService', 'BaseEnum', 'User', 'DataPushConst',
        function ($http, $q, Authentication, BaseFunction, EntityService, BaseEnum, User, DataPushConst) {
            return {
                getERPParamValues: getERPParamValues,
                httpPOSTErpSV: httpPOSTErpSV,
                getERPContext: getERPContext,
                saveSyncData: saveSyncData,
                updatePushDataState: updatePushDataState
            }

            //调用后台服务 获取 调用ERP服务的 ERPHostAddress，ERPPort，ERPVirtualDir 三个参数
            function getERPParamValues(successHandle, errHandle) {
                BaseFunction.request('/api/DataPush/getERPSysParamValues', false, null, successHandle, errHandle);
            };

            //HttpPost服务 调用U9
            function httpPOSTErpSV(svUrl, params, resultHandle) {
                getERPParamValues(function (result) {

                    var url = 'http://' + result.ERPHostAddress;
                    if (result.ERPPort) {
                        url += ':' + result.ERPPort;
                    }
                    if (result.ERPVirtualDir) {
                        url += '/' + result.ERPVirtualDir;
                    }
                    url += '/' + svUrl;

                    $http({
                        method: 'POST',
                        url: url,
                        data: params,
                        timeout: DataPushConst.httpTimeOut
                    }).success(function (result) {
                        resultHandle(null, result);
                    }).error(function (error) {
                        var newErr = new Error();
                        newErr.leval = 9;
                        newErr.title = '服务调用失败！'
                        newErr.message = 'ERP数据同步服务调用失败,请检查ERP网络环境是否正常！'
                        resultHandle(newErr);
                    });

                }, function (error) {
                    resultHandle(newErr);
                });

            };

            //保存同步数据
            function saveSyncData(data, entityFullName, resultHandle) {
                if (data == null) {
                    var newErr = new Error();
                    newErr.leval = 9;
                    newErr.title = '数据同步失败！'
                    newErr.message = '未获取到需要同步的数据，请检查！'
                    resultHandle(newErr);
                } else {
                    var newRecords = [];
                    var entityName = '';
                    if (entityFullName === DataPushConst.BarcodeMaster) {
                        entityName = 'BarcodeMaster';
                    } else if (entityFullName === DataPushConst.Org) {
                        entityName = 'Org';
                    } else if (entityFullName == DataPushConst.StorageLocation) {
                        entityName = "StorageLocation";
                    } else if (entityFullName == DataPushConst.Bin) {
                        entityName = "Bin";
                    } else if (entityFullName == DataPushConst.Supplier) {
                        entityName = "Supplier";
                    } else if (entityFullName == DataPushConst.Cusomer) {
                        entityName = "Customer";
                    }



                    for (var i = 0; i < data.d.length; i++) {

                        var objPushData = angular.fromJson(data.d[i].DataPushJson);

                        var newRecord = {};

                        if (entityFullName === DataPushConst.BarcodeMaster) {
                            newRecord.ID = -1;
                            newRecord.RowStatus = BaseEnum.RowStatus.Insert.Value;
                            newRecord.Barcode = objPushData.Code;
                            newRecord.ErpID = objPushData.ID;
                            // newRecord.EntityID=objPushData.EntityID;
                            // newRecord.EntityName=objPushData.EntityID;
                            newRecord.ErpBCType = objPushData.BarCodeType;
                            newRecord.BCRuleName = objPushData.BCRuleName;
                            newRecord.QtyType = objPushData.QtyType;
                            newRecord.Qty = objPushData.Qty;
                            newRecord.PrintPerson = objPushData.PrintPerson;
                            newRecord.IsPrint = objPushData.IsPrint;
                            newRecord.Segment1 = objPushData.Segment1;
                            newRecord.Segment2 = objPushData.Segment2;
                            newRecord.Segment3 = objPushData.Segment3;
                            newRecord.Segment4 = objPushData.Segment4;
                            newRecord.Segment5 = objPushData.Segment5;
                            newRecord.Segment6 = objPushData.Segment6;
                            newRecord.Segment7 = objPushData.Segment7;
                            newRecord.Segment8 = objPushData.Segment8;
                            newRecord.Segment9 = objPushData.Segment9;
                            newRecord.Segment10 = objPushData.Segment10;

                            newRecords.push(newRecord);
                        } else if (entityFullName === DataPushConst.Org) {

                            newRecord.ID = -1;
                            newRecord.RowStatus = BaseEnum.RowStatus.Insert.Value;
                            newRecord.ErpID = objPushData.ID;
                            newRecord.Code = objPushData.Code;
                            newRecord.Name = objPushData.Name;

                            newRecords.push(newRecord);
                        } else if (entityFullName == DataPushConst.StorageLocation) {

                            newRecord.ID = -1;
                            newRecord.RowStatus = BaseEnum.RowStatus.Insert.Value;
                            newRecord.ErpID = objPushData.ID;
                            newRecord.Code = objPushData.Code;
                            newRecord.Name = objPushData.Name;
                            newRecord.Org = objPushData.Org;
                            newRecord.OrgCode = objPushData.OrgCode;
                            newRecord.OrgName = objPushData.OrgName;
                            newRecord.Department = objPushData.Department;
                            newRecord.DepartmentCode = objPushData.DepartmentCode;
                            newRecord.DepartmentName = objPushData.DepartmentName;
                            newRecord.IsEffevtive = objPushData.IsEff;
                            newRecord.Dsc = objPushData.Dsc;

                            newRecords.push(newRecord);
                        } else if (entityFullName == DataPushConst.Bin) {

                            newRecord.ID = -1;
                            newRecord.RowStatus = BaseEnum.RowStatus.Insert.Value;
                            newRecord.ErpID = objPushData.ID;
                            newRecord.Code = objPushData.Code;
                            newRecord.Name = objPushData.Name;
                            newRecord.Org = objPushData.Org;
                            newRecord.OrgCode = objPushData.OrgCode;
                            newRecord.OrgName = objPushData.OrgName;
                            newRecord.Warehouse = objPushData.Warehouse;
                            newRecord.WarehouseCode = objPushData.WarehouseCode;
                            newRecord.WarehouseName = objPushData.WarehouseName;
                            newRecord.IsEffective = objPushData.IsEff;
                            newRecord.Dsc = objPushData.Dsc;

                            newRecords.push(newRecord);
                        } else if (entityFullName == DataPushConst.Supplier) {

                            newRecord.ID = -1;
                            newRecord.RowStatus = BaseEnum.RowStatus.Insert.Value;
                            newRecord.ErpID = objPushData.ID;
                            newRecord.Code = objPushData.Code;
                            newRecord.Name = objPushData.Name;
                            newRecord.Org = objPushData.Org;
                            newRecord.OrgCode = objPushData.OrgCode;
                            newRecord.OrgName = objPushData.OrgName;
                            newRecord.IsEffective = objPushData.IsEff;
                            newRecord.Dsc = objPushData.Dsc;

                            newRecords.push(newRecord);
                        } else if (entityFullName == DataPushConst.Cusomer) {

                            newRecord.ID = -1;
                            newRecord.RowStatus = BaseEnum.RowStatus.Insert.Value;
                            newRecord.ErpID = objPushData.ID;
                            newRecord.Code = objPushData.Code;
                            newRecord.Name = objPushData.Name;
                            newRecord.Org = objPushData.Org;
                            newRecord.OrgCode = objPushData.OrgCode;
                            newRecord.OrgName = objPushData.OrgName;
                            newRecord.IsEffective = objPushData.IsEff;
                            newRecord.Dsc = objPushData.Dsc;

                            newRecords.push(newRecord);
                        }
                    }

                    var saveDatas = [];
                    saveDatas.push({
                        EntityName: entityName,
                        Records: newRecords
                    });
                    var updateStateDatas = {
                        EntityName: entityFullName,
                        Records: newRecords
                    };

                    EntityService.saves(saveDatas, function (result) {
                        updatePushDataState(updateStateDatas, function (err, result) {
                            resultHandle(err, result);
                        })
                    },
                        function (error) {
                            resultHandle(error);
                        });
                }
            };
            //同步数据成功后  回写 同步数据日志表
            function updatePushDataState(data, resultHandle) {
                if (data == null) {
                    var newErr = new Error();
                    newErr.leval = 9;
                    newErr.title = '数据同步状态回写失败！'
                    newErr.message = '数据同步状态回写未获取到需要改写同步状态的数据，请检查！'
                    resultHandle(newErr);
                } else {
                    var entityName = data.EntityName
                    var EntityIDs = [];

                    for (var i = 0; i < data.Records.length; i++) {
                        EntityIDs.push(data.Records[i].ErpID);
                    }

                    getERPContext(function (err, context) {
                        if (err != null) {
                            resultHandle(err);
                        } else {
                            var params = {
                                context: context,
                                entityFullName: entityName,
                                entityIDs: EntityIDs
                            };

                            httpPOSTErpSV(DataPushConst.updatePushStateURL, params, function (err, result) {
                                if (err != null) {
                                    resultHandle(err);
                                } else {
                                    resultHandle(null, result);
                                }
                            });
                        }

                    });
                }
            };

            //获取上下文 信息
            function getERPContext(resultHandle) {

                var erpUserCode = '',
                    erpEntCode = '',
                    erpOrgCode = '';

                var user = User.getProfile();
                if (user == null) {
                    var newErr = new Error();
                    newErr.leval = 9;
                    newErr.title = '获取登录用户失败！'
                    newErr.message = '获取登录用户失败,无法完成同步数据,请检查是否正常登录系统！'
                    resultHandle(newErr);
                } else {

                    erpUserCode = user.ErpUserCode;
                    if (typeof (erpUserCode) == 'undefined') {
                        var newErr = new Error();
                        newErr.leval = 9;
                        newErr.title = '数据同步失败！'
                        newErr.message = '获取登录用户对应的ERP用户编码失败,无法完成同步数据,请检查是否正常设置！'
                        resultHandle(newErr);
                    } else {
                        erpEntCode = user.ErpEntCode;
                        if (typeof (erpEntCode) == 'undefined') {
                            var newErr = new Error();
                            newErr.leval = 9;
                            newErr.title = '数据同步失败！'
                            newErr.message = '获取登录用户对应的ERP企业编码失败,无法完成同步数据,请检查是否正常设置！'
                            resultHandle(newErr);
                        } else {
                            if (user.Orgs == null || user.Orgs.length == 0) {
                                var newErr = new Error();
                                newErr.leval = 9;
                                newErr.title = '数据同步失败！'
                                newErr.message = '获取登录用户对应的ERP组织编码失败,无法完成同步数据,请检查是否正常设置！'
                                resultHandle(newErr);
                            } else {
                                erpOrgCode = user.Orgs[0].Code;

                                var context = {
                                    CultureName: "zh-CN",
                                    EntCode: erpEntCode,
                                    OrgCode: erpOrgCode,
                                    UserCode: erpUserCode
                                };
                                resultHandle(null, context);
                            }
                        }
                    }
                }
            };
        }
    ]);